#include "stdafx.h"
#include "FSM.h"
#include "FSMState.h"

FSM::FSM()
{
	for (auto &s : m_states) s = nullptr;
}

FSM::~FSM()
{
	for (auto &s : m_states)
	{
		if (s)
		{
			delete s;
			s = nullptr;
		}
	}
}

void FSM::Update()
{
	//auto state = m_stateList.back();
	//switch (state->m_runState)
	//{
	//case FSMState::rs_run:
	//	state->Run();
	//	break;
	//case FSMState::rs_pause:
	//	if (state->Continue())
	//	{
	//		state->m_runState = FSMState::rs_run;
	//		state->Run();
	//	}
	//	break;
	//case FSMState::rs_exit:
	//	if (state->Enter())
	//	{
	//		state->m_runState = FSMState::rs_run;
	//		state->Run();
	//	}
	//	break;
	//default:
	//	break;
	//}
	if (m_currentState)
	{
		m_currentState->Run();
	}
	else
	{
		SetNextState(st_idle);
		ChangeToNextState();

	}
}
//
//void FSM::Push(State state)
//{
//	if (!m_states[state]) return;
//	if (m_stateList.size())
//	{
//		m_stateList.back()->Pause();
//		m_stateList.back()->m_runState = FSMState::rs_pause;
//	}
//	m_stateList.push_back(m_states[state]);
//}
//
//void FSM::Pop()
//{
//	m_stateList.back()->Exit();
//	m_stateList.back()->m_runState = FSMState::rs_exit;
//	m_stateList.pop_back();
//	if (m_stateList.empty()) m_stateList.push_back(m_defaultState);
//}
//
//void FSM::Replace(State state)
//{
//	if (!m_states[state]) return;
//	m_stateList.back()->Exit();
//	m_stateList.back()->m_runState = FSMState::rs_exit;
//	m_stateList.back() = m_states[state];
//}
//
//void FSM::Clear()
//{
//	while (m_stateList.size())
//	{
//		m_stateList.back()->Exit();
//		m_stateList.back()->m_runState = FSMState::rs_exit;
//		m_stateList.pop_back();
//	}
//	m_stateList.push_back(m_defaultState);
//}

void FSM::ChangeToNextState(State nextNextState)
{
	auto s = m_states[m_nextState];
	m_nextState = nextNextState;
	if (s)
	{
		m_currentState = s;
		if (m_currentState->Enter())
			m_currentState->Run();
	}
}

void FSM::SetNextState(State state)
{
	m_nextState = state;
}

void FSM::SetNextState_move(Move * move)
{
	m_nextState = st_move;
	if (move) m_move = *move;
}

void FSM::SetNextState_attack(Attack * attack)
{
	m_nextState = st_attack;
	if (attack) m_attack = *attack;
}

void FSM::SetNextState_dir(Dir * dir)
{
	m_nextState = st_dir;
	if (dir) m_dir = *dir;
}

FSM::State FSM::GetNextState()
{
	return m_nextState;
}


